﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Traceability.App.DTO;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Traceability
{
    public class TraceabilityDetailCommandHandler : IRequestHandler<TraceabilityDetailCommand, APIResult<TraceabilityListDto>>
    {
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IBaseRepository<T_Goods> goodsRepository;

        public TraceabilityDetailCommandHandler(IBaseRepository<T_Traceability> tranceRepository, IBaseRepository<T_Goods> goodsRepository)
        {
            this.tranceRepository = tranceRepository;
            this.goodsRepository = goodsRepository;
        }

        public Task<APIResult<TraceabilityListDto>> Handle(TraceabilityDetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<TraceabilityListDto> result = new APIResult<TraceabilityListDto>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            var list = (from a in tranceRepository.GetAll().AsNoTracking()
                        join b in goodsRepository.GetAll().AsNoTracking()
                        on a.SID equals b.ID
                        select new TraceabilityListDto
                        {
                            ID = a.ID,
                            SID = a.SID,
                            GoodsName = b.GoodsName,
                            Batch = a.Batch,
                            ShelfLife = a.ShelfLife,
                            LicenseNumber = a.LicenseNumber,
                            Manufacturers = a.Manufacturers,
                            CoverImageUrl = a.CoverImageUrl,
                            Perfection = a.Perfection,
                        }).FirstOrDefault(p => p.ID == request.ID);
            result.Data = list;
            return Task.FromResult(result);
        }
    }
}
